package com.previewlibrary;

import com.previewlibrary.enitity.IThumbViewInfo;
import com.previewlibrary.view.BasePhotoFragment;
import com.previewlibrary.view.PhotoPagerAdapter;
import com.previewlibrary.wight.BezierBannerView;
import com.previewlibrary.wight.PhotoViewPager;
import com.previewlibrary.wight.SmoothImageView;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.PageSlider;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * PhotoPagerAdapter.
 *
 * @author author
 * @version version
 */
public class GPreviewAbility extends Ability {

    private static final String TAG = GPreviewAbility.class.getName();
    /**
     * isTransformOut
     */
    protected boolean isTransformOut = false;
    /**
     * 图片的地址
     **/
    private List<IThumbViewInfo> imgUrls;
    /**
     * 当前图片的位置
     **/
    protected int currentIndex;
    /**
     * 图片的展示的Fragment
     **/
    private List<BasePhotoFragment> fragments = new ArrayList<>();
    /**
     * 展示图片的viewPager
     **/
    private PhotoViewPager viewPager;
    /**
     * 显示图片数
     **/
    private Text ltAddDot;
    /**
     * 指示器控件
     **/
    private BezierBannerView bezierBannerView;
    /**
     * 指示器类型枚举
     **/
    private GPreviewBuilder.IndicatorType type;
    /**
     * 默认显示
     **/
    private boolean isShow = true;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        // getWindow().setStatusBarColor(Color.TRANSPARENT.getValue());
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        getWindow().setTransparent(true);
        if (setContentLayout() == 0) {
            super.setUIContent(ResourceTable.Layout_ability_gpreview);
        } else {
            super.setUIContent(setContentLayout());
        }
        initData(intent);
        initView();
    }

    /**
     * 初始化数据
     *
     * @param intent intent
     */
    private void initData(Intent intent) {
        imgUrls = intent.getSequenceableArrayListParam("imagePaths");
        currentIndex = intent.getIntParam("position", 0);
        type = intent.getSerializableParam("type");
        isShow = intent.getBooleanParam("isShow", true);
        int duration = intent.getIntParam("duration", 400);
        boolean isFullscreen = intent.getBooleanParam("isFullscreen", false);
        boolean isScale = intent.getBooleanParam("isScale", false);
        SmoothImageView.setFullscreen(isFullscreen);
        SmoothImageView.setIsScale(isScale);
        try {
            SmoothImageView.setDuration(duration);
            Class<? extends BasePhotoFragment> sss;
            sss = intent.getSerializableParam("className");
            iniFragment(imgUrls, currentIndex, sss);
        } catch (Exception e) {
            iniFragment(imgUrls, currentIndex, BasePhotoFragment.class);
        }

    }

    /**
     * 初始化
     *
     * @param imgUrls      集合
     * @param currentIndex 选中索引
     * @param className    显示Fragment
     **/
    protected void iniFragment(List<IThumbViewInfo> imgUrls, int currentIndex, Class<? extends BasePhotoFragment> className) {
        if (imgUrls != null) {
            int size = imgUrls.size();
            for (int i = 0; i < size; i++) {
                BasePhotoFragment basePhotoFragment = BasePhotoFragment.getBasePhotoFragment(
                        this, className, imgUrls.get(i), currentIndex == i,
                        getIntent().getBooleanParam("isSingleFling", false),
                        getIntent().getBooleanParam("isDrag", false),
                        getIntent().getFloatParam("sensitivity", 0.5f));
                PageSlider pageSlider = (PageSlider) findComponentById(ResourceTable.Id_viewPager);
                basePhotoFragment.setPageSlider(pageSlider);
                fragments.add(basePhotoFragment);
            }
        } else {
            terminateAbility();
        }
    }

    private void initView() {
        viewPager = (PhotoViewPager) findComponentById(ResourceTable.Id_viewPager);
        // viewPager的适配器
        PhotoPagerAdapter adapter = new PhotoPagerAdapter(this);
        viewPager.setProvider(adapter);
        adapter.setItems(fragments);
        adapter.notifyDataChanged();
        viewPager.setCurrentPage(currentIndex);
        // viewPager.setOffscreenPageLimit(3);
        bezierBannerView = (BezierBannerView) findComponentById(ResourceTable.Id_bezierBannerView);
        ltAddDot = (Text) findComponentById(ResourceTable.Id_ltAddDot);
        if (type == GPreviewBuilder.IndicatorType.Dot) {
            bezierBannerView.setVisibility(Component.VISIBLE);
            bezierBannerView.attachToViewpager(viewPager);
        } else {
            ltAddDot.setVisibility(Component.VISIBLE);
            String format = String.format(Locale.ROOT, "%d%s%d", (currentIndex + 1), "/", imgUrls.size());
            ltAddDot.setText(format);

            viewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
                @Override
                public void onPageSliding(int i, float v, int i1) {

                }

                @Override
                public void onPageSlideStateChanged(int i) {

                }

                @Override
                public void onPageChosen(int position) {
                    // 当被选中的时候设置小圆点和当前位置
                    if (ltAddDot != null) {
                        String format = String.format(Locale.ROOT, "%d%s%d", (position + 1), "/", imgUrls.size());
                        ltAddDot.setText(format);
                    }
                    currentIndex = position;
                    viewPager.setCurrentPage(currentIndex, true);
                }
            });
        }
        if (fragments.size() == 1) {
            if (!isShow) {
                bezierBannerView.setVisibility(Component.HIDE);
                ltAddDot.setVisibility(Component.HIDE);
            }
        }
        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                BasePhotoFragment fragment = fragments.get(currentIndex);
                fragment.transformIn();
            }
        }, 100);
    }


    /**
     * 自定义布局内容.
     *
     * @return int
     **/
    public int setContentLayout() {
        return 0;
    }

    /**
     * 得到PhotoViewPager.
     *
     * @return PhotoViewPager
     **/
    public PhotoViewPager getViewPager() {
        return viewPager;
    }

    /**
     * 退出预览的动画.
     **/
    public void transformOut() {
        // 解决闪烁
        setPreviewRootBg(0x00000000);
        if (isTransformOut) {
            return;
        }
        getViewPager().setEnabled(false);
        getViewPager().setSlidingPossible(false);
        isTransformOut = true;
        int currentItem = viewPager.getCurrentPage();
        if (currentItem < imgUrls.size()) {
            BasePhotoFragment fragment = fragments.get(currentItem);
            if (ltAddDot != null) {
                ltAddDot.setVisibility(Component.HIDE);
            } else {
                bezierBannerView.setVisibility(Component.HIDE);
            }
            fragment.changeBg(Color.TRANSPARENT.getValue());
            fragment.transformOut(new SmoothImageView.OnTransformListener() {
                @Override
                public void onTransformCompleted(SmoothImageView.Status status) {
                    getViewPager().setEnabled(true);
                    exit();
                }
            });
        } else {
            exit();
        }
    }

    /**
     * 关闭页面.
     */
    private void exit() {
        if (isTerminating()) {
            return;
        }
        terminateAbility();
        setTransitionAnimation(0, 0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        BasePhotoFragment.setListener(null);
    }

    @Override
    protected void onBackPressed() {
        isTransformOut = false;
        transformOut();
    }

    public void setPreviewRootBg(int color) {
        if (isTerminating()) {
            return;
        }
        Component root = findComponentById(ResourceTable.Id_preview_root);
        if (root != null) {
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setRgbColor(RgbColor.fromArgbInt(color));
            root.setBackground(shapeElement);
        }
    }
}
